"""
django-cheetahtemplate

Justin Quick & Dirk Van Oosterbosch
http://code.google.com/p/django-cheetahtemplate
Version 0.2
"""
from django.template import Template as DjangoTemplate
from django.template import Context
from django.http import HttpResponse
from django.template.loader import find_template_source
try:
    from Cheetah.Template import Template
except ImportError:
    raise ImportError, 'You must have Cheetah templating library installed. Get it at http://www.cheetahtemplate.org/download.html'
        
class CheetahTemplate(object):
    """
    Cheetah template class which can render Django Contexts. Takes text to render
    """
    def __init__(self, text):
        self.text = text
        self.searchList = []
        
    def render(self, context):
        return str(Template(self.text, searchList=list(context.dicts)))

def render_cheetah_response(template_name, dictionary, context_instance=None):
    """
    Returns a HttpResponse whose content is filled with the result of CheetahTemplate.render
    """
    template_instance = CheetahTemplate(find_template_source(template_name)[0])
    if context_instance:
        context_instance.update(dictionary)
    else:
        context_instance = Context(dictionary)        
    return template_instance.render(context_instance)


def render_to_response(*args, **kwargs):
    """
    Wrapper around render_cheetah_response which is just like django.shortcuts.render_to_response
    Returns a HttpResponse whose content is filled with the result of calling
    django_cheetahtemplates.render_cheetah_response with the passed arguments.
    """
    httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
    return HttpResponse(render_cheetah_response(*args, **kwargs), **httpresponse_kwargs)